package com.wolfpire.system.dao.impl;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.wolfpire.system.common.base.dao.impl.BaseHibernateDao;
import com.wolfpire.system.common.util.StringUtils;
import com.wolfpire.system.dao.UserRoleRelationDao;
import com.wolfpire.system.model.UserRoleRelation;

@Repository("userRoleRelationDao")
public class UserRoleRelationDaoImpl extends BaseHibernateDao<UserRoleRelation, Long> implements UserRoleRelationDao {
	
	@Override
	public void relate(Long userId, Long[] roleIds) {
		//先删除后绑定
		this.deleteByUserId(userId);
		if (!ArrayUtils.isEmpty(roleIds)) {
			for (Long roleId : roleIds) {
				UserRoleRelation ur = new UserRoleRelation(userId, roleId);
				this.saveOrUpdate(ur);
			}
		}
	}
	
	public void deleteByUserId(Long userId) {
		String executeSql = "DELETE FROM t_sm_user_role WHERE user_id = ?";
		this.executeSql(executeSql, userId);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<UserRoleRelation> getURRelation(Long userId) {
		Criteria c = createCriteria().add(Restrictions.eq("userId", userId))
				.add(Restrictions.isNotNull("roleId"));
		return c.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<UserRoleRelation> getRURelation(Long roleId) {
		Criteria c = createCriteria().add(Restrictions.eq("roleId", roleId));
		return c.list();
	}

	@Override
	public void relate(Long userId, List<Long> roleIds) {
		this.deleteByUserId(userId);
		if (CollectionUtils.isNotEmpty(roleIds)) {
			Session session = this.getSession();
			int size = roleIds.size();
			for (int i = 0; i < size; i++) {
				UserRoleRelation ur = new UserRoleRelation(userId, roleIds.get(i));
				session.save(ur);
				if ((i + 1) % 50 == 0) {
					session.flush();
					session.clear();
				}
			}
		}
	}

	@Override
	public void relateRoleUsers(Long roleId, String userIdsStr) {
		this.deleteByRoleId(roleId);
		if (!StringUtils.isBlank(userIdsStr)) {
			String[] userIdsArr = userIdsStr.split(",");
			int length = userIdsArr.length;
			Session session = this.getSession();
			for (int i = 0; i < length; i++) {
				UserRoleRelation ur = new UserRoleRelation(Long.parseLong(userIdsArr[i]), roleId);
				session.save(ur);
				if ((i + 1) % 50 == 0) {
					session.flush();
					session.clear();
				}
			}
		}
	}

	private void deleteByRoleId(Long roleId) {
		String executeSql = "DELETE FROM t_sm_user_role WHERE role_id = ?";
		this.executeSql(executeSql, roleId);
	}

}
